package org.kitrum.example.tomcat;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.kitrum.example.tomcat.servlet.HelloServlet;

/**
 * Tomcat 配置方式启动类
 *
 * @author : Kun
 * @version : 1.0
 * @date : 2021/01/21 18:59
 **/
public class TomcatApplication {

    public static void run() {
        //创建tomcat对象
        Tomcat tomcat = new Tomcat();
        //配置端口号
        tomcat.setPort(8100);
        //创建上下文
        StandardContext context = new StandardContext();
        //设置项目名
        context.setPath("/foo");
        //监听上下文
        context.addLifecycleListener(new Tomcat.FixContextListener());
        //向tomcat容器添加上下文配置
        tomcat.getHost().addChild(context);
        //添加Servlet
        Wrapper wrapper = Tomcat.addServlet(context, "helloServlet", new HelloServlet());
//        tomcat.addServlet("/foo", "helloServlet", new HelloServlet());
        //设置启动顺序，默认-1,如果>0在启动tomcat的时候会调用Servlet.init()方法
        wrapper.setLoadOnStartup(1);
        //添加servlet映射关系
        context.addServletMappingDecoded("/hello", "helloServlet");
        try {
            //启动tomcat
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        run();
    }
}
